package mail;

import dataobject.MailMess;
import org.apache.commons.lang3.StringUtils;
import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;

import javax.mail.internet.MimeMessage;


/**
 * @ Type : com.weiyi.ehr.monitor.mail
 * @ Author : TimLi
 * @ Desc :
 * @ Date : 2016-07-06 15:57
 */
public class MailFactory {


    private JavaMailSender mailSender;

    private SimpleMailMessage simpleMailMessage;

    public void setSimpleMailMessage(SimpleMailMessage simpleMailMessage) {
        this.simpleMailMessage = simpleMailMessage;
    }

    public void setMailSender(JavaMailSender mailSender) {
        this.mailSender = mailSender;
    }

	public void sendMail(MailMess mailMess) throws Exception {

        MimeMessage mimeMessage = mailSender.createMimeMessage();
        try {
            MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMessage,true);
            messageHelper.setFrom(simpleMailMessage.getFrom());
            messageHelper.setSubject(mailMess.getSubObejct());
            messageHelper.setText(mailMess.getBody());
            messageHelper.setTo(mailMess.getToEamilUsers());
            if(StringUtils.isNotBlank(mailMess.getFilePath())) {
                FileSystemResource file = new FileSystemResource(mailMess.getFilePath());
                messageHelper.addAttachment(file.getFilename(), file); //添加附件
            }
            mailSender.send(mimeMessage);    //发送附件邮件
        } catch (Exception e) {
            throw new Exception("发送邮件异常");
        }


    }
}
